import json
import os
import random
import time

from django.conf import settings
from django.http import JsonResponse
from rest_framework import viewsets, status, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.club_system.club.models import ClubMember, Club
from apps.common.account.models import Account
from apps.common.school.models import Faculty
import datetime


class VisualizationViewSet(viewsets.GenericViewSet):
    @action(['get'], detail=False, url_path='data')
    def visualization(self, request):
        # 1、各个社团的人数统计
        # 2、各个学院的人数统计
        # 3、各个社团的活动数统计
        # 社团成员人数、活动数

        club_count = 0  # 总社团数
        member_count = 0  # 社团成员总数
        clubs = Club.objects.filter(first_check_status='通过', second_check_status='通过', is_active=True).order_by('id')
        club_members = [['社团名称', '成员数量']]  # 每个社团的成员数
        for club in clubs:
            club_count += 1
            # 目前 is_active 的成员
            count = club.club_member.filter(is_active=True).count()
            member_count += count
            tmp = [club.name, count]
            club_members.append(tmp)


        today = datetime.datetime.now()

        # 社团正在招新的个数
        now_apply_club_count = Club.objects.filter(first_check_status='通过', second_check_status='通过', is_active=True,
                                                   apply_end_time__gt=today, apply_start_time__lt=today).count()

        bar_chart_data = {'source': club_members, 'title': '各社团成员数量'}

        result = {'bar_chart_data': bar_chart_data, 'club_count': club_count,
                  'now_apply_club_count': now_apply_club_count, }
        return Response(result, status=status.HTTP_200_OK)


class UploadViewSet(GenericViewSet, mixins.CreateModelMixin):
    @action(methods=['post'], detail=False, url_path='images')
    def upload(self, request, *args, **kwargs):
        image = request.data.get('image', None)
        dir_name = request.data.get('dir_name', '')
        if not all([image, dir_name]):
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        dir_path = f"{settings.MEDIA_ROOT}/{dir_name}"
        if not os.path.exists(dir_path):  # 没有该目录就创建
            os.makedirs(dir_path)
        # 给文件重新命名，避免重复
        now_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        # name, suffix = os.path.splitext(image.name)
        # new_filename = now_str + name + suffix
        file_name = image.name
        new_filename = f"{random.randint(100, 999)}-{now_str}-{file_name}"
        img_path = os.path.join(dir_path, new_filename)
        # 写入文件
        with open(img_path, 'ab') as fp:
            # 如果上传的文件非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in image.chunks():
                fp.write(chunk)
        img_path = f'{dir_name}/{new_filename}'
        data = {
            'url': f'{settings.IMAGE_URL}{img_path}',
            'alt': new_filename,
        }
        result = {'errno': 0, 'data': data}
        return JsonResponse(result)

    @action(methods=['post'], detail=False, url_path='upload_img')
    def upload_img(self, request, pk=None):
        """ 上传图片/文件 """
        file = request.data.get('file', None)
        dir_name = request.data.get('dir_name', '')
        if not all([file, dir_name]):
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        file_name = file.name
        dir_path = f"{settings.MEDIA_ROOT}/club_system/{dir_name}"
        if not os.path.exists(dir_path):  # 没有该目录就创建
            os.makedirs(dir_path)
        # 给文件重新命名，避免重复
        now_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        new_file_name = f"{random.randint(100, 999)}-{now_str}-{file_name}"
        img_path = os.path.join(dir_path, new_file_name)
        # 写入文件
        with open(img_path, 'ab') as fp:
            # 如果上传的文件非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in file.chunks():
                fp.write(chunk)
        img_path = f'club_system/{dir_name}/{new_file_name}'
        return Response({'data': img_path, 'file_name': new_file_name})


# 定时任务
def AutoQuit():
    try:
        # 定时任务,毕业自动退团
        import datetime
        today = datetime.datetime.today()
        year = today.year - 4
        account_ids = Account.objects.filter(grade_name__contains=str(year)).values_list('id', flat=True)
        ids = ClubMember.objects.select_related('account').filter(account_id__in=list(account_ids)).values_list('id',
                                                                                                                flat=True)
        tmp = [ClubMember(id=i, is_active=False) for i in list(ids)]
        ClubMember.objects.bulk_update(tmp, fields=['is_active'])
        print("hello")
    except Exception as e:
        print('发生错误，错误信息为：', e)
